import json
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from user.models import *
from flow.models import *
from flow.serializer import *
from user.serializer import *
from util.jwt_token import check_login
from util.qiniuyun_token import qiniu_token
from salary.serializer import *
from django.db import models


# 工资条
class SalaryView(ViewSet):

    # 获取全部工资条
    @check_login
    def salary_list(self, request):
        try:
            salary = Salary.objects.all()
            ser = SalarySer(salary, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取失败", "data": ser.data})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 添加工资条
    @check_login
    def salary_add(self, request):
        try:
            name = request.data.get("name")
            # 出勤
            attendance = request.data.get("attendance")
            # 旷工
            absenteeism = request.data.get("absenteeism")
            # 请假
            leave = request.data.get("leave")
            # 基本工资
            basesalary = request.data.get("basesalary")
            # 岗位工资
            postsalary = request.data.get("postsalary")

            print("数据", request.data)

            if not all([name, attendance, absenteeism, leave, basesalary, postsalary]):
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

            user = UserModel.objects.filter(name=name).count()
            if user == 0:
                return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "没有此员工"})

            users = UserModel.objects.filter(name=name, is_delete=0)
            users_ser = UserSer(users, many=True).data
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)

            # 查询出职位
            user_id = self._cuser.id
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            ser = UserSer(user).data
            user_list = PositionModel.objects.filter(id=ser["position"]).first()
            # 查询出职级
            rank = RankModel.objects.filter(id=user_list.rank_id).first()
            # 查询出部门
            dept = DeptModel.objects.filter(id=user_list.dept_id).first()
            dept_ser = DeptSer(dept).data
            depts = json.loads(json.dumps(dept_ser))

            if depts["name"] != "财务部":
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "您不是财务部员工，不能添加工资条!!!"})

            salary = Salary.objects.filter(is_delete=False, user_id=name).first()
            if salary:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此员工本月已经有工资条"})

            Salary.objects.create(user_id=name, gate=attendance, absent=absenteeism,
                                  leave=leave, base_money=basesalary, station_money=postsalary)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加失败"})

    # 删除工资条
    def salary_delete(self, request, pk):
        try:
            salary = Salary.objects.filter(id=pk, is_delete=False)
            salary.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 获取工资条
    def salary_info(self, request, pk):
        try:
            salary = Salary.objects.filter(id=pk, is_delete=False).first()
            ser = SalarySer(salary)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功", "data": ser.data})
        except Exception as e:
            print("删除失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除失败"})

    # 修改工资条
    def salary_update(self, request, pk):
        try:
            name = request.data.get("name")
            # 出勤
            attendance = request.data.get("attendance")
            # 旷工
            absenteeism = request.data.get("absenteeism")
            # 请假
            leave = request.data.get("leave")
            # 基本工资
            basesalary = request.data.get("basesalary")
            # 岗位工资
            postsalary = request.data.get("postsalary")

            print("数据", request.data)

            user = UserModel.objects.filter(name=name).count()
            if user == 0:
                return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "没有此员工"})

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users, many=True).data
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)

            Salary.objects.filter(id=pk).update(user_id=name, gate=attendance, absent=absenteeism,
                                  leave=leave, base_money=basesalary, station_money=postsalary)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改失败"})

    # 搜索工资条
    def search(self, request):
        name = request.data.get("name")
        account = request.data.get("account")
        mobile = request.data.get("mobile")

        print("数据", request.data)

        try:
            user_name = UserModel.objects.filter(models.Q(name=name) | models.Q(account=account) | models.Q(mobile=mobile)).count()
            if user_name == 0:
                return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "没有此员工"})

            users = UserModel.objects.filter(is_delete=False)
            users_ser = UserSer(users, many=True).data
            list = []
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)

                if i.get("account") == account:
                    account = i.get("id")
                    print("account", account)

                if i.get("mobile") == mobile:
                    mobile = i.get("id")
                    print("mobile", mobile)

            salary = Salary.objects.filter(models.Q(user_id=name) | models.Q(user_id=account) | models.Q(user_id=mobile)).all()

            ser = SalarySer(salary, many=True)

            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("搜索失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 我发起的流程
class initiationsView(ViewSet):

    # 我申请的流程
    def initiations_add(self, request):
        name = request.data.get("name")
        approvaltype = request.data.get("approvaltype")
        applicationtime = request.data.get("applicationtime")
        approver = request.data.get("approver")
        sector = request.data.get("sector")
        print(request.data)

        try:
            user = UserModel.objects.filter(is_delete=False)
            user_ser = UserSer(user, many=True)
            for i in user_ser.data:
                if i.get("name") == name:
                    name = i.get("id")
            print("当前的name:", name)

            type = TypeModel.objects.filter(is_delete=False)
            type_ser = TypeSer(type, many=True)
            for i in type_ser.data:
                if i.get("name") == approvaltype:
                    approvaltype = i.get("id")
                    template = i.get("template_id")
                    template = Template.objects.get(id=template)
                    templates_ser = TemplateSer(template).data
                    flow = FlowModel.objects.get(id=templates_ser["id"])
                    flow_ser = FlowSer(flow).data
                    flow_id = flow_ser["id"]
            print("approvaltype", approvaltype)
            print("flow_id", flow_id)

            dept = DeptModel.objects.filter(is_delete=False)
            dept_ser = DeptSer(dept, many=True)
            for i in dept_ser.data:
                if i.get("name") == sector:
                    sector = i.get("id")
            print("sector", sector)

            data = {
                "flow": flow_id,
                "vettypes": approvaltype,
                "user_name": name,
                "vettime": applicationtime,
                "level": "2"
            }
            print("data", data)
            ser = FlowNodeSer(data=data)
            ser.is_valid()

            FlowNodeModel.objects.create(flow_id=flow_id, vettype_id=approvaltype, vettsatus=0, name_id=name,
                                         vettime=applicationtime, level_id=1)
            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取我的流程
    def initiations_list(self, request):
        id = request.data.get("id")
        print("id", id)

        try:
            flow_node = FlowNodeModel.objects.filter(name_id=id)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data
            # print("flow_node_ser", flow_node_ser)
            user = UserModel.objects.filter(id=id)
            user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
            for flow_node in flow_node_ser:
                for user in user_ser.data:
                    position_id = user.get("position")
                    print("position_id", position_id)
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    for position in position_ser.data:
                        flow_node["department"] = position.get("departmentname")
                if int(flow_node.get("vettsatus")) == 0:
                    flow_node["vettsatus"] = "未审批"

                elif int(flow_node.get("vettsatus")) == 1:
                    flow_node["vettsatus"] = "同意"

                elif int(flow_node.get("vettsatus")) == 2:
                    flow_node["vettsatus"] = "驳回"
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": flow_node_ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取我发起的流程详情
    def initiations_info(self, request, pk):
        try:
            flow_node = FlowNodeModel.objects.filter(id=pk).first()
            flow_node_ser = FlowNodeSer(flow_node).data
            # print("---", flow_node_ser)
            user = UserModel.objects.filter(id=flow_node_ser.get("name"))
            user_ser = UserSer(user, many=True)

            print("user_ser", user_ser.data)
            for user in user_ser.data:
                position_id = user.get("position")
                position = PositionModel.objects.filter(id=position_id)
                position_ser = PositionSer(position, many=True)
                for position in position_ser.data:
                    flow_node_ser["department"] = position.get("departmentname")
            if int(flow_node_ser.get("vettsatus")) == 0:
                flow_node_ser["vettsatus"] = "未审批"

            elif int(flow_node_ser.get("vettsatus")) == 1:
                flow_node_ser["vettsatus"] = "同意"

            elif int(flow_node_ser.get("vettsatus")) == 2:
                flow_node_ser["vettsatus"] = "驳回"

            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": flow_node_ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 撤销我发起的流程
    def initiations_delete(self, request, pk):
        try:
            flow_node = FlowNodeModel.objects.filter(id=pk, is_delete=False)
            if not flow_node:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "流程不存在"})

            flow_node.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "撤销成功"})
        except Exception as e:
            print("撤销失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "撤销失败"})


# 待办事项
class TodosView(ViewSet):

    # 获取所有待办事项
    @check_login
    def todos_list(self, request):
        try:
            flow_node = FlowNodeModel.objects.filter(is_delete=False, vettsatus=0)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data

            for i in flow_node_ser:
                # 先查找出用户
                user = UserModel.objects.filter(id=i.get("id"))
                user_ser = UserSer(user, many=True)
                # 根据用户查找职位 然后在查找部门
                for user in user_ser.data:
                    position_id = user.get("position")
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    print(position_ser.data)
                    for j in position_ser.data:
                        i["department"] = j.get("dept_name")

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_node_ser})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 搜索待办事项
    def search(self, request):
        # 申请人
        name = request.data.get("name")
        # 审批类型
        vettype = request.data.get("vettype")
        # 审批状态
        vettstatus = request.data.get("vettstatus")

        print(request.data)

        try:

            user = UserModel.objects.filter(name=name, is_delete=False)
            users_ser = UserSer(user, many=True).data
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)

            type = TypeModel.objects.filter(name=vettype, is_delete=False)
            type_ser = TypeSer(type, many=True).data
            for i in type_ser:
                if i.get("name") == vettype:
                    vettype = i.get("id")
                    print("vettype", vettype)

            flow_node = FlowNodeModel.objects.filter(models.Q(name_id=name) | models.Q(vettype_id=vettype) | models.Q(vettsatus=vettstatus))
            ser = FlowNodeSer(flow_node, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})

    # 获取待办事项详情
    def todos_info(self, request, pk):
        try:
            flow_node = FlowNodeModel.objects.filter(id=pk, is_delete=False)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data

            for i in flow_node_ser:
                # 先查找出用户
                user = UserModel.objects.filter(id=i.get("id"))
                user_ser = UserSer(user, many=True)
                # 根据用户查找职位 然后在查找部门
                for user in user_ser.data:
                    position_id = user.get("position")
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    print(position_ser.data)
                    for j in position_ser.data:
                        i["department"] = j.get("dept_name")

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_node_ser})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})


# 待办事项(通过)
class ThroughViews(APIView):
    def post(self, request, pk):
        try:
            FlowNodeModel.objects.filter(id=pk).update(vettsatus=1)
            return Response({"code": status.HTTP_200_OK,"msg": '通过成功'})
        except Exception as e:
            print("通过",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 待办事项(驳回)
class DisallowedViews(APIView):
    def post(self, request, pk):
        try:
            FlowNodeModel.objects.filter(id=pk).update(vettsatus=2)
            return Response({"code": status.HTTP_200_OK,"msg": '驳回成功'})
        except Exception as e:
            print("驳回",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 获取已办事项
class DonesView(ViewSet):

    # 获取所有已办事项
    @check_login
    def dones_list(self, request):
        try:
            flow_node = FlowNodeModel.objects.filter(is_delete=False, vettsatus=1)
            flow_node_ser = FlowNodeSer(flow_node, many=True).data

            for i in flow_node_ser:
                # 先查找出用户
                user = UserModel.objects.filter(id=i.get("id"))
                user_ser = UserSer(user, many=True)
                # 根据用户查找职位 然后在查找部门
                for user in user_ser.data:
                    position_id = user.get("position")
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    print(position_ser.data)
                    for j in position_ser.data:
                        i["department"] = j.get("dept_name")

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_node_ser})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取已办事项详情
    def dones_info(self, request, pk):
        try:
            flow_node = FlowNodeModel.objects.filter(id=pk, is_delete=False)
            flow_node_ser = FlowNodeSer(flow_node, many=True)

            print("flow_node_ser", flow_node_ser.data)

            for i in flow_node_ser.data:
                print("user", i.get("id"))
                user = UserModel.objects.filter(id=i.get("id"))
                user_ser = UserSer(user, many=True)

                for user in user_ser.data:
                    position_id = user.get("position")
                    position = PositionModel.objects.filter(id=position_id)
                    position_ser = PositionSer(position, many=True)
                    print(position_ser.data)
                    for j in position_ser.data:
                        i["department"] = j.get("dept_name")

            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_node_ser.data})
        except Exception as e:
            print("获取失败",e )
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 搜索待办事项
    def search(self, request):
        # 申请人
        name = request.data.get("name")
        # 审批类型
        vettype = request.data.get("vettype")
        # 审批状态
        vettstatus = request.data.get("vettstatus")

        print(request.data)

        try:

            user = UserModel.objects.filter(name=name, is_delete=False)
            users_ser = UserSer(user, many=True).data
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    print("name", name)

            type = TypeModel.objects.filter(name=vettype, is_delete=False)
            type_ser = TypeSer(type, many=True).data
            for i in type_ser:
                if i.get("name") == vettype:
                    vettype = i.get("id")
                    print("vettype", vettype)

            flow_node = FlowNodeModel.objects.filter(
                models.Q(name_id=name) | models.Q(vettype_id=vettype) | models.Q(vettsatus=vettstatus))
            ser = FlowNodeSer(flow_node, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


# 邮件
class EmailView(ViewSet):

    # 发送邮件
    @check_login
    def send_mail(self, request):
        # 当前登录的用户 就是发件人
        user_id = self._cuser.id
        print("user_id", user_id)
        # title 标题 address_url 地址 name 收件人  content 内容
        title = request.data.get("sendertitle")
        address_url = request.data.get("senderadder")
        name = request.data.get("sendername")
        content = request.data.get("sendercontent")

        print("数据", request.data)

        try:
            user = UserModel.objects.filter(name=name, is_delete=False)
            users_ser = UserSer(user, many=True).data
            for i in users_ser:
                if i.get("name") == name:
                    name = i.get("id")
                    # 接收人
                    print("name", name)

            MailModel.objects.create(title=title, user_id=user_id, users_id=name, content=content, address_url=address_url)
            return Response({'code': status.HTTP_200_OK, 'msg': '发送成功'})

        except Exception as e:
            print("发送失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "发送失败"})

    # 接收邮件
    @check_login
    def receive_mail(self, request):
        user_id = self._cuser.id
        print("user_id", user_id)

        try:
            list = MailModel.objects.filter(users_id=user_id, is_delete=False).all()

            ser = MailSer(list, many=True)

            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})

        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})
